package com.example.warehouse_manager.controller;

import com.example.warehouse_manager.entity.*;
import com.example.warehouse_manager.service.AuthService;
import com.example.warehouse_manager.service.UserService;
import com.example.warehouse_manager.utils.DigestUtil;
import com.example.warehouse_manager.utils.TokenUtils;
import com.example.warehouse_manager.utils.WarehouseConstants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    //注入DefaultKaptcha的bean对象，生成验证码图片
    @Resource(name = "captchaProducer")
    private Producer producer;

    //注入redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    //token工具类
    @Autowired
    private TokenUtils tokenUtils;


    //生成验证码图片的接口
    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response){

        ServletOutputStream out = null;
        try {
            //生成验证码图片的文件
            String text = producer.createText();
            //使用验证码文本生成验证码图片,BufferedImage就代表内存中生成的验证码图片
            BufferedImage image = producer.createImage(text);
            //将验证码文本作为键保存到redis,设置五分钟的过期时间
            redisTemplate.opsForValue().set(text,"",60*5, TimeUnit.SECONDS);


            //设置响应正文
            response.setContentType("image/jpeg");
            //将验证码图片响应给前端
            out = response.getOutputStream();
            ImageIO.write(image,"jpg",out);
            //刷新
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭流
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }


    //登录
    //@RequestBody LoginUser loginUser表示接收并且封装前端传过来的json信息
    //返回Result对象，向前端响应Result对象转换的json串
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){

        //拿到用户登录的验证码
        String verificationCode = loginUser.getVerificationCode();
        if (!(redisTemplate.hasKey(verificationCode))){
            return Result.err(Result.CODE_ERR_BUSINESS,"验证码错误");
        }

        //根据账号查询用户
        User user = userService.queryUserByCode(loginUser.getUserCode());
        if (user != null){//账号存在
            if (user.getUserState().equals(WarehouseConstants.USER_STATE_PASS)){//用户已审核

                //获取用户输入的密码
                String userPwd = loginUser.getUserPwd();
                //进行md5加密
                userPwd = DigestUtil.hmacSign(userPwd);
                if (userPwd.equals(user.getUserPwd())){//密码正确

                    //生成jwt token并存储到redis
                    CurrentUser currentUser =
                            new CurrentUser(user.getUserId(), user.getUserCode(),user.getUserName());
                    String token = tokenUtils.loginSign(currentUser, userPwd);
                    //向客户端响应
                    return Result.ok("登录成功",token);

                }else {//密码错误
                    return Result.err(Result.CODE_ERR_BUSINESS,"密码错误");
                }
            }else {//用户未审核
                return Result.err(Result.CODE_ERR_BUSINESS,"用户未审核");
            }
        }else {//账号不存在
            return Result.err(Result.CODE_ERR_BUSINESS,"账号不存在");
        }
    }


    //获取当前登录的用户信息的url接口
    //@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)
    //表示将请求头（前端归还的）Token的值赋值给请求处理方法入参变量token
    @RequestMapping("/curr-user")
    public Result currentUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //解析token拿到封装了当前登录用户信息的CurrentUser对象
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        return Result.ok(currentUser);
    }


    //加载用户权限菜单树的url接口
    @RequestMapping("/user/auth-list")
    public Result loadAuthTree(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //拿到当前登录的用户id
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int userId = currentUser.getUserId();

        //执行业务
        List<Auth> authTree = authService.findAuthTree(userId);

        //响应给前端
        return Result.ok(authTree);
    }

    //退出登录
    @RequestMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //从redis中删除token键
        redisTemplate.delete(token);
        return Result.ok("退出系统");
    }


}
